<template>
  <div class="category-management">
    <div class="page-header">
      <h1>分类管理</h1>
      <p>管理系统中的所有商品分类</p>
    </div>

    <div class="content-card">
      <div class="toolbar">
        <input type="text" v-model="searchName" placeholder="输入分类名称搜索" class="search-input">
        <button class="btn btn-primary" @click="searchCategories">搜索</button>
        <button class="btn btn-primary" @click="showAddModal">新增分类</button>
      </div>

      <div class="table-container">
        <table class="category-table">
          <thead>
            <tr>
              <th>分类ID</th>
              <th>分类名称</th>
              <th>父级分类</th>
              <th>层级</th>
              <th>图标</th>
              <th>显示状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="category in categories" :key="category.categoryId">
              <td>{{ category.categoryId }}</td>
              <td>{{ category.categoryName }}</td>
              <td>{{ getParentCategoryName(category.parentId) }}</td>
              <td>
                <span :class="['level-badge', `level-${category.categoryLevel}`]">
                  {{ category.categoryLevel === 1 ? '一级' : '二级' }}
                </span>
              </td>
              <td>
                <span class="category-icon">{{ category.icon || '📁' }}</span>
              </td>
              <td>
                <span :class="['status', category.isShow === 1 ? 'show' : 'hide']">
                  {{ category.isShow === 1 ? '显示' : '隐藏' }}
                </span>
              </td>
              <td>{{ formatDate(category.createTime) }}</td>
              <td>
                <button class="btn btn-edit" @click="editCategory(category)">编辑</button>
                <button class="btn btn-delete" @click="deleteCategory(category)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增/编辑分类模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑分类' : '新增分类' }}</h3>
          <button class="close-btn" @click="closeModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveCategory">
            <div class="form-row">
              <div class="form-group">
                <label>分类名称 *</label>
                <input type="text" v-model="editingCategory.categoryName" required>
              </div>
              <div class="form-group">
                <label>分类层级</label>
                <select v-model="editingCategory.categoryLevel" @change="onLevelChange">
                  <option value="1">一级分类</option>
                  <option value="2">二级分类</option>
                </select>
              </div>
              <div class="form-group">
                <label>分类图标</label>
                <input type="text" v-model="editingCategory.icon" placeholder="🔧">
              </div>
            </div>
            <div class="form-row" v-if="editingCategory.categoryLevel == 2">
              <div class="form-group">
                <label>父级分类 *</label>
                <select v-model="editingCategory.parentId" required>
                  <option value="">请选择父级分类</option>
                  <option v-for="parent in parentCategories" :key="parent.categoryId" :value="parent.categoryId">
                    {{ parent.categoryName }}
                  </option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label>显示状态</label>
              <select v-model="editingCategory.isShow">
                <option value="1">显示</option>
                <option value="0">隐藏</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">{{ isEditing ? '保存' : '新增' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getAllCategories, addCategory, updateCategory, deleteCategory, searchCategoriesByName } from '@/api/admin';

export default {
  name: 'CategoryManagement',
  data() {
    return {
      categories: [],
      searchName: '',
      showModal: false,
      isEditing: false,
      editingCategory: {
        categoryName: '',
        parentId: '',
        categoryLevel: 1,
        icon: '',
        isShow: 1
      },
      loading: false
    }
  },
  computed: {
    parentCategories() {
      return this.categories.filter(cat => cat.categoryLevel === 1);
    }
  },
  mounted() {
    this.fetchCategories();
  },
  methods: {
    async fetchCategories() {
      try {
        this.loading = true;
        console.log('开始获取分类数据...');
        const response = await getAllCategories();
        console.log('分类API响应:', response);
        this.categories = response || [];
        console.log('分类数据:', this.categories);
      } catch (error) {
        console.error('获取分类列表失败:', error);
        console.error('错误详情:', error.response || error);
        alert('获取分类列表失败: ' + error.message);
      } finally {
        this.loading = false;
      }
    },
    getParentCategoryName(parentId) {
      if (!parentId) return '-';
      const parent = this.categories.find(cat => cat.categoryId === parentId);
      return parent ? parent.categoryName : '未知';
    },
    formatDate(dateString) {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    },
    showAddModal() {
      this.isEditing = false;
      this.editingCategory = {
        categoryName: '',
        parentId: '',
        categoryLevel: 1,
        icon: '',
        isShow: 1
      };
      this.showModal = true;
    },
    editCategory(category) {
      this.isEditing = true;
      this.editingCategory = { ...category };
      this.showModal = true;
    },
    onLevelChange() {
      if (this.editingCategory.categoryLevel === 1) {
        this.editingCategory.parentId = '';
      }
    },
    async saveCategory() {
      try {
        let response;
        if (this.isEditing) {
          response = await updateCategory(this.editingCategory);
        } else {
          response = await addCategory(this.editingCategory);
        }
        
        if (response.includes('successfully')) {
          alert(this.isEditing ? '分类修改成功' : '分类添加成功');
          this.closeModal();
          this.fetchCategories();
        } else {
          alert('操作失败');
        }
      } catch (error) {
        console.error('保存分类失败:', error);
        alert('保存分类失败');
      }
    },
    async deleteCategory(category) {
      if (!confirm(`确定要删除分类 "${category.categoryName}" 吗？`)) {
        return;
      }
      
      try {
        const response = await deleteCategory(category.categoryId);
        if (response.includes('successfully')) {
          alert('分类删除成功');
          this.fetchCategories();
        } else {
          alert('删除失败');
        }
      } catch (error) {
        console.error('删除分类失败:', error);
        alert('删除分类失败');
      }
    },
    closeModal() {
      this.showModal = false;
      this.editingCategory = {};
    },
    async searchCategories() {
      if (!this.searchName.trim()) {
        this.fetchCategories();
        return;
      }
      try {
        this.loading = true;
        const response = await searchCategoriesByName(this.searchName);
        this.categories = response || [];
      } catch (error) {
        alert('搜索失败: ' + error.message);
      } finally {
        this.loading = false;
      }
    }
  }
}
</script>

<style scoped>
.category-management {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 2rem;
}

.page-header p {
  margin: 0;
  color: #7f8c8d;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  overflow: hidden;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ecf0f1;
}

.table-container {
  overflow-x: auto;
}

.category-table {
  width: 100%;
  border-collapse: collapse;
}

.category-table th,
.category-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ecf0f1;
}

.category-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.category-table tr:hover {
  background-color: #f8f9fa;
}

.level-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
}

.level-badge.level-1 {
  background-color: #e8f5e8;
  color: #2e7d32;
}

.level-badge.level-2 {
  background-color: #e3f2fd;
  color: #1976d2;
}

.category-icon {
  font-size: 1.2rem;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875rem;
}

.status.show {
  background-color: #d4edda;
  color: #155724;
}

.status.hide {
  background-color: #f8d7da;
  color: #721c24;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
  margin-right: 5px;
  transition: all 0.3s ease;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-edit {
  background-color: #f39c12;
  color: white;
}

.btn-edit:hover {
  background-color: #e67e22;
}

.btn-delete {
  background-color: #e74c3c;
  color: white;
}

.btn-delete:hover {
  background-color: #c0392b;
}

.btn-secondary {
  background-color: #95a5a6;
  color: white;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ecf0f1;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #7f8c8d;
}

.modal-body {
  padding: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 15px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #2c3e50;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.875rem;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #3498db;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style> 